package com.veng.springbootdemo.controller;

import com.veng.springbootdemo.utils.ResponseUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class LoginController {
    @GetMapping(value = "login")
    public String login(){
        return "login";
    }

    /**
     * Subject： 代表当前正在执行操作的用户，但Subject代表的可以是人，也可以是任何第三方系统帐号。
     * 当然每个subject实例都会被绑定到SercurityManger上
     * @param username
     * @param password
     * @return
     */
    @PostMapping(value = "ajaxLogin")
    @ResponseBody
    public Map login(@RequestParam("username")String username, @RequestParam("password")String password){
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e){
            return ResponseUtils.toJson(10,"未知账户",null);
        }catch (IncorrectCredentialsException e){
            return ResponseUtils.toJson(11,"密码不正确",null);
        }catch (AuthenticationException e){
            return ResponseUtils.toJson(12,"用户名或密码不正确",null);
        }
        if (subject.isAuthenticated()) {
            return ResponseUtils.toJson(200,"登录成功",null);
        }else {
            usernamePasswordToken.clear();
            return ResponseUtils.toJson(400,"登录失败",null);
        }
    }

    @RequestMapping("/403")
    public String unauthorizedRole(){
        System.out.println("------没有权限-------");
        return "403";
    }
}
